import hashlib
from rest_framework.response import Response
from rest_framework.views import APIView

from course.models import CourseModel, NperModel, ShufflingModel
from users.models import UserModel, CollectionModel, TeacherModel, OrderModel, ShoppingCartModel
import json
from django.core import serializers

from utils import verify
from utils.phone import is_phone


# 注册
class RegisterView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            # name = request.POST['name']
            # phone = request.POST['phone']
            # password = request.POST['password']
            a = json.loads(request.body)
            name = a['name']
            phone = a['phone']
            password = a['password']
        except:
            data = {
                'msg': "用户提交的参数有误",
                'code': 4000,
            }
            return Response(data)
        else:
            if all([name, phone, password]) and is_phone(phone):
                user = UserModel.objects.filter(phone=phone)
                if len(user) != 0:
                    data = {
                        'msg': "用户信息有误",
                        'code': 4000,
                    }
                    return Response(data)
                else:
                    UserModel.objects.create(name=name, phone=phone, password=password)
                    da = {}
                    da['phone'] = phone
                    da['password'] = password
                    da['name'] = name
                    data = {
                        'msg': "注册成功",
                        'code': 2000,
                        'data': da
                    }
                    return Response(data)

            else:
                data = {
                    'msg': "手机号或者密码或者手机号格式不正确",
                    'code': 4000,
                }
                return Response(data)


# 登录
class LoginView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            # phone = request.POST['phone']
            # password = request.POST['password']
            a = json.loads(request.body)
            phone = a['phone']
            password = a['password']
        except:
            data = {
                'msg': "用户提交的参数有误",
                'code': 4000,
            }
            return Response(data)
        else:
            if all([phone, password]) and is_phone(phone):
                user = UserModel.objects.filter(phone=phone, status=0)
                if len(user) == 0:
                    data = {
                        'msg': "没有查询到此用户",
                        'code': 4000,
                    }
                    return Response(data)
                else:
                    username = json.loads(serializers.serialize("json", user))[0]
                    pwd = username['fields']['password']
                    sha_pwd = hashlib.sha256(password.encode("utf-8")).hexdigest()
                    if sha_pwd == pwd:
                        da = {}
                        da['phone'] = phone
                        da['password'] = password
                        da['userName'] = username['fields']['name']
                        data = {
                            'msg': "登录成功",
                            'code': 2000,
                            'data': da
                        }
                        return Response(data)
                    else:
                        data = {
                            'msg': "密码验证不通过",
                            'code': 4000,
                        }
                        return Response(data)
            else:
                data = {
                    'msg': "手机号或密码有误或者手机号格式不正确",
                    'code': 4000,
                }
                return Response(data)


# 修改密码
class UpdateView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            a = json.loads(request.body)
            phone = a['phone']
            password = a['password']
            new_password = a['new_password']
            # phone = request.POST['phone']
            # password = request.POST['password']
            # new_password = request.POST['new_password']

        except:
            data = {
                'msg': "用户提交的参数有误",
                'code': 4000,
            }
            return Response(data)
        else:
            if all([phone, password, new_password]) and is_phone(phone):
                user = UserModel.objects.filter(phone=phone, status=0)
                if len(user) == 0:
                    data = {
                        'msg': "没有查询到此用户",
                        'code': 4000,
                    }
                    return Response(data)
                else:
                    username = json.loads(serializers.serialize("json", user))[0]
                    pwd = username['fields']['password']
                    sha_pwd = hashlib.sha256(password.encode("utf-8")).hexdigest()
                    if sha_pwd == pwd:
                        UserModel.objects.filter(phone=phone, status=0).update(
                            password=hashlib.sha256(new_password.encode("utf-8")).hexdigest())
                        data = {
                            'msg': "修改成功",
                            'code': 2000,
                        }
                        return Response(data)
                    else:
                        data = {
                            'msg': "密码验证不通过",
                            'code': 4000,
                        }
                        return Response(data)
            else:
                data = {
                    'msg': "手机号或密码有误或者手机号格式不正确",
                    'code': 4000,
                }
                return Response(data)

    # def get(self,request):
    #     UserModel.objects.filter(phone='13111119999', status=0).update(password=hashlib.sha256('123'.encode("utf-8")).hexdigest())
    #     return Response("aaa")


# 修改信息
class InformationView(APIView):
    def post(self, request, *args, **kwargs):
        return Response('手机号有误')


# 忘记密码
class ForgetView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            phone = request.POST['phone']
        except:
            data = {
                'msg': "用户提交的参数有误",
                'code': 4000,
            }
            return Response(data)
        else:
            if all([phone]) and is_phone(phone):
                user = UserModel.objects.filter(phone=phone, status=0)
                if len(user) == 0:
                    data = {
                        'msg': "没有查询到此用户",
                        'code': 4000,
                    }
                    return Response(data)
                else:
                    UserModel.objects.filter(phone=phone, status=0).update(
                        password=hashlib.sha256('123456'.encode("utf-8")).hexdigest())
                    data = {
                        'msg': "修改成功",
                        'code': 2000,
                    }
                    return Response(data)
            else:
                data = {
                    'msg': "手机号有误或者手机号格式不正确",
                    'code': 4000,
                }
                return Response(data)


# 用户收藏
class CollectionView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            # phone = request.POST['phone']
            # id = request.POST['id']
            a = json.loads(request.body)
            phone = a['phone']
            id = a['id']
            share_user = a['share_user']
        except:
            data = {
                'msg': "用户提交的参数有误",
                'code': 4000,
            }
            return Response(data)
        else:
            u = UserModel.objects.filter(phone=phone)
            c = CourseModel.objects.filter(id=id)
            if len(u) == 0 or len(c) == 0:
                data = {
                    'msg': "没找到用户或项目",
                    'code': 4000,
                }
                return Response(data)
            else:
                c1 = json.loads(serializers.serialize("json", c))[0]
                name = c1['fields']['name']
                introduce = c1['fields']['introduce']
                money = c1['fields']['money']
                n = NperModel.objects.filter(id=c1['fields']['nper'])
                n1 = json.loads(serializers.serialize("json", n))[0]
                number = n1['fields']['number']
                apply = n1['fields']['apply']
                residue = n1['fields']['residue']
                apply_start_time = n1['fields']['apply_start_time']
                apply_end_time = n1['fields']['apply_end_time']
                start_time = n1['fields']['start_time']
                end_time = n1['fields']['end_time']
                learning = n1['fields']['learning']
                CollectionModel.objects.create(project=id, phone=phone, name=name, introduce=introduce, money=money,
                                               number=number, apply_start_time=apply_start_time,
                                               apply_end_time=apply_end_time, start_time=start_time, end_time=end_time,
                                               learning=learning, share_user=share_user)
                data = {
                    'msg': "收藏成功",
                    'code': 2000,
                }
                return Response(data)


# 查询用户收藏记录
class QueryCollectionView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            a = json.loads(request.body)
            phone = a['phone']
        except:
            data = {
                'msg': "用户手机号不正确",
                'code': 4000,
            }
            return Response(data)
        else:
            c = CollectionModel.objects.filter(phone=phone)
            if len(c) == 0:
                data = {
                    'msg': "暂无收藏数据",
                    'code': 4000,
                }
                return Response(data)
            else:
                c1 = json.loads(serializers.serialize("json", c))
                data_list = []
                for i in c1:
                    data_dict = {}
                    data_dict['name'] = i['fields']['name']
                    data_dict['id'] = i['fields']['project']
                    data_dict['introduce'] = i['fields']['introduce']
                    data_dict['money'] = i['fields']['money']
                    data_dict['number'] = i['fields']['number']
                    ccc = CourseModel.objects.filter(id=i['fields']['project'])
                    ccc1 = json.loads(serializers.serialize("json", ccc))[0]
                    data_dict['image'] = ccc1['fields']['image']
                    data_list.append(data_dict)
                data = {
                    'msg': "查询成功",
                    'code': 2000,
                    'data': data_list
                }
                return Response(data)


# 用户订单
class UserOrderView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            a = json.loads(request.body)
            phone = a['phone']
            # products = a['products']
            id = a['products']
            num = a['num']
            share_user = a['share_user']
            print("id", id)
        except:
            print('ssss', a['share_user'])
            data = {
                'msg': "用户输入的参数不正确",
                'code': 4000,
            }
            return Response(data)
        else:
            u = UserModel.objects.filter(phone=phone)
            c = CourseModel.objects.filter(id=id)
            if len(u) == 0 or len(c) == 0:
                data = {
                    'msg': "没有找到用户或者是项目，提交失败",
                    'code': 4000,
                }
                return Response(data)
            else:
                num_order = verify.number()
                c1 = json.loads(serializers.serialize("json", c))[0]
                name = c1['fields']['name']
                money = c1['fields']['money']
                image = c1['fields']['image']
                introduce = c1['fields']['introduce']
                n = NperModel.objects.filter(id=c1['fields']['nper'])
                n1 = json.loads(serializers.serialize("json", n))[0]
                numb = n1['fields']['number']
                apply = n1['fields']['apply']
                residue = n1['fields']['residue']
                apply_start_time = n1['fields']['apply_start_time']
                apply_end_time = n1['fields']['apply_end_time']
                start_time = n1['fields']['start_time']
                end_time = n1['fields']['end_time']
                learning = n1['fields']['learning']
                if verify.datatime_check(apply_start_time, apply_end_time) or (int(residue) > 0):
                    NperModel.objects.filter(id=c1['fields']['nper']).update(apply=(int(apply) + int(num)),
                                                                             residue=(int(residue) - int(num)))
                    OrderModel.objects.create(number=num_order, phone=phone, project=id, course_name=name, money=money,
                                              num=num,
                                              introduce=introduce, course_number=numb,
                                              apply_start_time=apply_start_time, apply_end_time=apply_end_time,
                                              start_time=start_time, end_time=end_time, learning=learning,
                                              share_user=share_user)
                    ss = ShoppingCartModel.objects.filter(project=id)
                    if len(ss) == 0:
                        pass
                    else:
                        ShoppingCartModel.objects.filter(project=id).delete()
                    data = {
                        'msg': "下单成功",
                        'code': 2000,
                    }
                    return Response(data)
                else:
                    data = {
                        'msg': "不在时间范围内或者预约已满",
                        'code': 4000,
                    }
                    return Response(data)


# 用户购物车
class SetCartView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            a = json.loads(request.body)
            phone = a['phone']
            product_id = a['product_id']
            share_user = a['share_user']
        except:
            data = {
                'msg': "用户输入的参数不正确",
                'code': 4000,
            }
            return Response(data)
        else:

            u = UserModel.objects.filter(phone=phone)
            c = CourseModel.objects.filter(id=product_id)
            if len(u) == 0 or len(c) == 0:
                data = {
                    'msg': "没有找到该用户或者该项目",
                    'code': 4000,
                }
                return Response(data)
            else:
                s = ShoppingCartModel.objects.filter(project=product_id)
                if len(s) == 0:
                    c1 = json.loads(serializers.serialize("json", c))[0]
                    name = c1['fields']['name']
                    introduce = c1['fields']['introduce']
                    money = c1['fields']['money']
                    image = c1['fields']['image']
                    n = NperModel.objects.filter(id=c1['fields']['nper'])
                    n1 = json.loads(serializers.serialize("json", n))[0]
                    number = n1['fields']["number"]
                    apply_end_time = n1['fields']["apply_end_time"]
                    start_time = n1['fields']["start_time"]
                    end_time = n1['fields']["end_time"]
                    learning = n1['fields']["learning"]
                    apply_start_time = n1['fields']["apply_start_time"]

                    ShoppingCartModel.objects.create(project=product_id, name=name, num=1, introduce=introduce,
                                                     money=money, image=image,
                                                     number=number, apply_start_time=apply_start_time,
                                                     apply_end_time=apply_end_time, start_time=start_time,
                                                     end_time=end_time, learning=learning, phone=phone,
                                                     share_user=share_user)
                    da = {}
                    da['name'] = name
                    da['introduce'] = introduce
                    da['money'] = money
                    da['image'] = image
                    da['number'] = number
                    da['apply_end_time'] = apply_end_time
                    da['start_time'] = start_time
                    da['end_time'] = end_time
                    da['learning'] = learning
                    da['apply_start_time'] = apply_start_time
                    data = {
                        'msg': "添加购物车成功",
                        'code': 2000,
                        'data': da
                    }
                    return Response(data)
                else:
                    s1 = json.loads(serializers.serialize("json", s))[0]
                    num = s1['fields']['num']
                    money = s1['fields']['money']
                    ShoppingCartModel.objects.filter(project=product_id).update(num=int(num) + 1,
                                                                                money=(int(money)) * (int(num) + 1))
                    data = {
                        'msg': "添加购物车成功",
                        'code': 2001,
                    }
                    return Response(data)


# 查询购物车信息
class QueryCardView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            a = json.loads(request.body)
            phone = a['phone']

        except:
            data = {
                'msg': "用户输入的参数不正确",
                'code': 4000,
            }
            return Response(data)
        else:
            u = UserModel.objects.filter(phone=phone)
            if len(u) == 0:
                data = {
                    'msg': "没有找到该用户",
                    'code': 4000,
                }
                return Response(data)
            else:
                s = ShoppingCartModel.objects.filter(phone=phone)
                if len(s) == 0:
                    data = {
                        'msg': "没有收藏记录",
                        'code': 2001,
                    }
                    return Response(data)
                else:
                    s1 = json.loads(serializers.serialize("json", s))
                    data_list = []
                    for i in s1:
                        data_dict = {}
                        data_dict['id'] = i['pk']
                        data_dict['productID'] = i['fields']['project']
                        data_dict['productName'] = i['fields']['name']
                        data_dict['num'] = i['fields']['num']
                        data_dict['productImg'] = i['fields']['image']
                        data_dict['introduce'] = i['fields']['introduce']
                        data_dict['price'] = i['fields']['money']
                        data_dict['number'] = i['fields']['number']
                        data_dict['apply_start_time'] = i['fields']['apply_start_time']
                        data_dict['apply_end_time'] = i['fields']['apply_end_time']
                        data_dict['start_time'] = i['fields']['start_time']
                        data_dict['end_time'] = i['fields']['end_time']
                        data_dict['learning'] = i['fields']['learning']
                        data_dict['phone'] = i['fields']['phone']
                        data_dict['check'] = True
                        data_list.append(data_dict)

                    data = {
                        'msg': "添加购物车成功",
                        'code': 2000,
                        'data': data_list
                    }
                    return Response(data)


# 从购物车中删除
class DelCartView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            a = json.loads(request.body)
            phone = a['phone']
            product_id = a['product_id']
        except:
            data = {
                'msg': "用户输入的参数不正确",
                'code': 4000,
            }
            return Response(data)
        else:
            u = UserModel.objects.filter(phone=phone)
            s = ShoppingCartModel.objects.filter(project=product_id)
            if len(u) == 0 or len(s) == 0:
                data = {
                    'msg': "用户名或项目不存在",
                    'code': 4000,
                }
                return Response(data)
            else:
                ShoppingCartModel.objects.filter(project=product_id).delete()
                data = {
                    'msg': "删除成功",
                    'code': 2000,
                }
                return Response(data)


# 查询订单
class QueryOrderView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            a = json.loads(request.body)
            phone = a['phone']
        except:
            data = {
                'msg': "用户输入的参数不正确",
                'code': 4000,
            }
            return Response(data)
        else:
            u = UserModel.objects.filter(phone=phone)
            if len(u) == 0:
                data = {
                    'msg': "没有查询到此用户，请注册",
                    'code': 4000,
                }
                return Response(data)
            else:
                o = OrderModel.objects.filter(phone=phone)
                if len(o) == 0:
                    data = {
                        'msg': "改用户没有下单记录",
                        'code': 4000,
                    }
                    return Response(data)
                else:
                    o1 = json.loads(serializers.serialize("json", o))
                    data_list = []
                    for i in o1:
                        data_list.append(i["fields"])
                    data = {
                        'msg': "查询成功",
                        'code': 2000,
                        'data': data_list
                    }
                    return Response(data)


# 分享获利
class ShareView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            a = json.loads(request.body)
            phone = a['phone']
        except:
            data = {
                'msg': "用户输入的参数不正确",
                'code': 4000,
            }
            return Response(data)
        else:
            o = OrderModel.objects.filter(phone=phone, share_user=phone)
            if len(o) == 0:
                data = {
                    'msg': "没有分享获利",
                    'code': 4000,
                }
                return Response(data)
            else:
                o1 = json.loads(serializers.serialize("json", o))
                data_list = []
                sum_money = 0
                for i in o1:

                    data_dict = {}

                    data_dict['course_name'] = i['fields']['course_name']
                    data_dict['num'] = i['fields']['num']
                    data_dict['money'] = i['fields']['money']
                    data_dict['order_time'] = i['fields']['order_time']
                    data_dict['interest'] = int(i['fields']['num']) * int(i['fields']['money']) * 0.1
                    sum_money +=int(i['fields']['num']) * int(i['fields']['money']) * 0.1
                    data_list.append(data_dict)

                data = {
                    'msg': "查询成功",
                    'code': 2000,
                    'sum_money':sum_money,
                    'data': data_list
                }
                return Response(data)
